# coding=utf-8

import os
import csv
import json
import shutil
import time

csv_file = 'i18nText.csv'
output_js_file = 'i18nText.ts'

def load_csv(csv_path):
    ''' load csv file and get row data '''

    res = {}
    with open(csv_path, mode='r', encoding='utf-8') as f:
        rd = csv.reader(f)

        h = next(rd)
        l = len(h)
        for item in h[2:]:
            res[item] = {}

        # get row data
        for row in rd:
            for i in range(2, l):
                if row[0] not in res[h[i]]:
                    res[h[i]][row[0]] = {}
                if len(row) > i:
                    res[h[i]][row[0]][row[1]] = row[i]
                else:
                    res[h[i]][row[0]][row[1]] = ''

    return res


def gen_js_file(data, js_path):
    ''' generate js file '''

    t = 'export default ' + json.dumps(data, ensure_ascii=False, indent=2)
    if os.path.exists(js_path):
        shutil.move(js_path, js_path + '.bak' + str(time.time()))

    with open(js_path, 'w', encoding='utf-8') as f:
        f.write(t)


if __name__ == '__main__':
    csv_path = os.path.join(os.path.dirname(__file__), csv_file)
    data = load_csv(csv_path)

    js_path = os.path.join(os.path.dirname(__file__), output_js_file)
    gen_js_file(data, js_path)

